package com.eastfair.pay.chinaums.common;

import com.eastfair.pay.chinaums.common.utils.OpenHttpClient;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author yuntu
 * @description 通过OPEN-BODY-SIG认证方式访问接口
 * @date 2020/6/9
 */
public class AccessByOpenBodySign {
    //todo 1、使用开放平台接口文档提供的测试参数和URL
    static String appid = "10037e6f6823b20801682b6a5e5a0006";
    static String appkey = "1c4e3b16066244ae9b236a09e5b312e8";
    //static String url = "http://58.247.0.18:29015/v1/smart-campus/chongqing/c2b-qrcode";
    static String url = "https://test-api-open.chinaums.com/v1/smart-campus/chongqing/c2b-qrcode";

    public static void main(String[] args) throws Exception{
        //todo 2. 根据实际接口文档组建请求报文;
        String reqBody = getRequestMsg_c2b_qrCode();
        System.out.println("reqBody:" + reqBody);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String authorization = getAuthorization(appid,appkey,sdf.format(new Date()),"nonce",reqBody);
        System.out.println("authorization:\n"+authorization);

        //String response = OpenHttpClient.request(url,authorization,reqBody);
        String response = OpenHttpClient.request_https(url,authorization,reqBody);
        System.out.println("response:\n"+response);
    }

    /**
     * 生成请求报文
     */
    public static String getRequestMsg_c2b_qrCode() throws Exception {
        C2BQrCodeReq c2BQrCodeReq = new C2BQrCodeReq();
        return c2BQrCodeReq.toString();
    }

    static class C2BQrCodeReq{
        String toJson(){
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            sb.append("\"payMchntNo\":\"" + "103201171229395" + "\",");
            sb.append("\"payTermNo\":\"" + "01171229" + "\",");
            sb.append("\"billTime\":\"" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "\",");
            sb.append("\"transAmt\":\"" + "1" + "\",");
            if (sb.charAt(sb.length() - 1) == ','){
                sb.deleteCharAt(sb.length() - 1);
            }
            sb.append("}");
            return sb.toString();
        }

        @Override
        public String toString(){
            return this.toJson();
        }

    }

    /**
     * 获取签名头
     * @param appid
     * @param appkey
     * @param timestamp 格式:"yyyyMMddHHmmss"
     * @param nonce 随机字符串，
     * @param body 请求体
     * @return authorization 认证报文
     * @throws Exception
     */
    static String getAuthorization(String appid, String appkey, String timestamp, String nonce, String body) throws Exception {
        byte[] data = body.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(data);
        String testSH = DigestUtils.sha256Hex(is);
        String s1 = appid+timestamp+nonce+testSH;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(appkey.getBytes("utf-8"),"HmacSHA256"));
        byte[] localSignature = mac.doFinal(s1.getBytes("utf-8"));
        String localSignatureStr = Base64.encodeBase64String(localSignature);
        return  "OPEN-BODY-SIG AppId="+"\""+appid+"\""+", Timestamp="+"\""+timestamp+"\""+", Nonce="+"\""+nonce+"\""+", Signature="+"\""+localSignatureStr+"\"";
    }

}
